package com.sanron.sunweather.activities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.View;

import com.sanron.sunweather.R;
import com.sanron.sunweather.action.LocationAction;
import com.sanron.sunweather.action.LocationAction.OnLocationListener;
import com.sanron.sunweather.action.WeatherAction;
import com.sanron.sunweather.action.WeatherAction.OnGetDataListener;
import com.sanron.sunweather.common.Config;
import com.sanron.sunweather.entity.City;
import com.sanron.sunweather.entity.WeatherData;
import com.sanron.sunweather.event.AboveEvent;
import com.sanron.sunweather.event.SelectCityEvent;
import com.sanron.sunweather.fragment.AboveFrag;
import com.sanron.sunweather.fragment.BaseFragment;
import com.sanron.sunweather.fragment.ExtrasFrag;
import com.sanron.sunweather.fragment.LifeIndexFrag;
import com.sanron.sunweather.fragment.MenuFrag;
import com.sanron.sunweather.utils.CommonUtils;
import com.sanron.sunweather.utils.NetUtils;
import com.sanron.sunweather.view.RotateView;
import com.sanron.sunweather.view.v4.DrawerLayout;
import com.sanron.sunweather.view.v4.DrawerLayout.DrawerListener;

import de.greenrobot.event.EventBus;

public class MainActivity extends FragmentActivity implements OnGetDataListener{

	private Config config;
	private DrawerLayout drawerLayout;
	private View contentView;
	private View menuView;
	
	private FragmentManager fm;
	private AboveFrag aboveFrag;
	private MenuFrag menuFrag;
	private EventBus eventBus;
	
	public static final String TAG_EXTRAS = "extras";
	public static final String TAG_LIFE_INDEX = "lifeindex";

	private Map<String,WeatherData> weatherDatas;
	private int currentCityPosition = 0;//当前显示城市的位置
	private String currentCity;//当前显示城市
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		eventBus = EventBus.getDefault();
		eventBus.register(this);
		init();
	}

	private void initView(){
		contentView = findViewById(R.id.content);
		menuView = findViewById(R.id.menu_container);
		drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
		drawerLayout.setDrawerListener(new DrawerListener() {
			@Override
			public void onDrawerStateChanged(int newState) {}
			@Override
			public void onDrawerOpened(View drawerView) {}
			@Override
			public void onDrawerClosed(View drawerView) {}
			@Override
			public void onDrawerSlide(View drawerView, float slideOffset) {
				//滑动菜单时滚动主内容
				int x = (int) (slideOffset*menuView.getMeasuredWidth());
				contentView.scrollTo(x, 0);
			}
		});
	}

	private void initData(){
		CommonUtils.loadCities(MainActivity.this);
		config = Config.getInstance(this);
		weatherDatas = new HashMap<String, WeatherData>();
	}
	
	private void init(){
		
		initView();
		initData();
		
		aboveFrag = new AboveFrag();
		menuFrag = new MenuFrag();
		menuFrag.setWeatherDatas(weatherDatas);
		menuFrag.setCities(config.getCities());
		fm = getSupportFragmentManager();
		fm.beginTransaction()
				.add(R.id.fragment_container_above,aboveFrag,"above")
				.add(R.id.menu_container,menuFrag,"menu")
				.commit();
		fm.addOnBackStackChangedListener(new OnBackStackChangedListener() {
			@Override
			public void onBackStackChanged() {
				//fragment回退栈空时
				if(fm.getBackStackEntryCount()==0){
					aboveFrag.setCenterVisiable(true);
					aboveFrag.setTopVisiable(true);
					aboveFrag.setRotateViewState(RotateView.STATE_UP);
				}
			}
		});

		if(config.isLocation()){
			if(NetUtils.checkNetwork(this)){
				//有网络
				aboveFrag.setLocationState("获取位置 ");
				LocationAction.getInstance(this).requestLocation(new OnLocationListener() {
					@Override
					public void onLocationSuccess(City city) {
						aboveFrag.setLocationState("定位到 "+city.getName());
						aboveFrag.setLocationState("请求数据");
						WeatherAction.getInstance().getWeahterData(city, new OnGetDataListener() {
							
							@Override
							public void onSuccess(final WeatherData weatherData) {
								String cityName = weatherData.getCity();
								weatherDatas.put(cityName,weatherData);
								config.setPrimaryCity(cityName);
								config.setLocationPrimaryCity(true);
								aboveFrag.setLocationState("");
								currentCity = cityName;
								refreshFragments();
							}
							
							@Override
							public void onError(String error) {
								aboveFrag.setLocationState("获取数据失败");
							}
						});
					}
					@Override
					public void onLocationFailed() {
						aboveFrag.setLocationState("定位失败");
					}
				});
			}else{
				//无网络连接
				aboveFrag.setLocationState("网络不可用");
			}
		}
	}
	
	
	public void onEventMainThread(AboveEvent event){
		switch(event.type){
		case AboveEvent.TYPE_TOP_MENU_CLICK:{
			//显示/隐藏侧滑菜单
			if(drawerLayout.isDrawerOpen(Gravity.RIGHT)){
				drawerLayout.closeDrawer(Gravity.RIGHT);
			}else{
				drawerLayout.openDrawer(Gravity.RIGHT);
			}
		}break;
		
		case AboveEvent.TYPE_BOTTOM_STATE_CHANGE:{
			int state = (Integer) event.obj;
			if(state==RotateView.STATE_UP){
				clearFragmentBackStack();
			}else if(state==RotateView.STATE_DOWN){
				switchFragment(TAG_LIFE_INDEX);
			}
		}break;
		
		case AboveEvent.TYPE_CENTER_CLICK:{
			//显示空气环境等额外信息
			switchFragment(TAG_EXTRAS);
		}break;
		
		}
	}

	//切换城市
	public void onEventMainThread(SelectCityEvent event){
		currentCityPosition = event.getSelectPosition();
		currentCity = config.getCities().get(currentCityPosition);
		refreshFragments();
	}
	
	/**
	 * 清空fragment回退栈
	 */
	private void clearFragmentBackStack(){
		while(fm.getBackStackEntryCount()>0){
			fm.popBackStackImmediate();
		}
	}
	
	/**
	 * 切换fragment
	 */
	public void switchFragment(String tag){
		FragmentTransaction transaction = fm.beginTransaction();
		BaseFragment baseFragment = null;
		transaction.setCustomAnimations(
				R.anim.slide_up,
				R.anim.slide_down,
				R.anim.slide_up,
				R.anim.slide_down);
		
		if(TAG_EXTRAS.equals(tag)){
			baseFragment = new ExtrasFrag();
			aboveFrag.setRotateViewState(RotateView.STATE_HIDE);
		}else if(TAG_LIFE_INDEX.equals(tag)){
			baseFragment = new LifeIndexFrag();
			aboveFrag.setTopVisiable(false);
			aboveFrag.setRotateViewState(RotateView.STATE_DOWN);
		}
		aboveFrag.setCenterVisiable(false);

		baseFragment.setWeatherData(weatherDatas.get(currentCity));
		transaction.add(R.id.fragment_container_behind,baseFragment, tag);
		transaction.addToBackStack(null);
		transaction.commitAllowingStateLoss();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch(requestCode){
		case MenuFrag.REQUEST_ADD_CITY:{
			if(resultCode == Activity.RESULT_OK){
				//添加城市
				City newCity = (City) data.getSerializableExtra("newCity");
				if(!config.getCities().contains(newCity.getName())){
					config.addCity(newCity.getName());
					WeatherAction.getInstance().getWeahterData(newCity,this);
					refreshFragments();
				}
			}
		}break;
		}
	}
	
	/**
	 * 通知所有fragment刷新视图
	 */
	private void refreshFragments(){
		List<Fragment> fragments = fm.getFragments();
		WeatherData weatherData = weatherDatas.get(currentCity);
		for(Fragment frag:fragments){
			((BaseFragment)frag).setWeatherData(weatherData);
			((BaseFragment)frag).refreshViews();
		}
	}
	
	@Override
	protected void onDestroy() {
		eventBus.unregister(this);
		super.onDestroy();
	}

	@Override
	public void onSuccess(WeatherData weatherData) {
		weatherDatas.put(weatherData.getCity(), weatherData);
		refreshFragments();
	}

	@Override
	public void onError(String error) {
	}
	
	@Override
	public void onBackPressed() {
		if(drawerLayout.isDrawerOpen(Gravity.RIGHT)){
			drawerLayout.closeDrawer(Gravity.RIGHT);
			return;
		}
		super.onBackPressed();
	}
}
